<?php

class ApplicationControllerImpl extends ApplicationController
{

  const MESSAGES_NOTICES = 'notices';

  const MESSAGES_WARNINGS = 'warnings';

  protected $messages;

  protected $menu;

  public function menu()
  {
    if (empty($this->menu)) {
      $this->menu = new Menu();

      $this->menu->addItem(new MenuItem('accounts', 'Accounts', null, null, array(
        new MenuItem('users', 'Users', '/admin/users'),
        new MenuItem('add_user', 'Add user', array('/admin/users', array('action' => 'create'))),
        new MenuItem('groups', 'Groups', null, null, array(
          new MenuItem('groups', 'Groups', '/admin/users/groups'),
          new MenuItem('add_group', 'Add group', array('/admin/users/groups', array('action' => 'create')))
        )),
        new MenuItem('permissions', 'Permissions', null, null, array(
          new MenuItem('permissions', 'Permissions', '/admin/users/permissions'),
          new MenuItem('add_permission', 'Add permission', array('/admin/users/permissions', array('action' => 'create')))
        )),
      )));
    }

    return $this->menu;
  }

  public function dispatch()
  {
    $this->messages = Session::getInstance()->flash('messages');

    $response = parent::dispatch();

    if ($response === false) {
      Session::getInstance()->flash('messages', $this->messages);
    }

    return $response;
  }

  public function messages($type, $msgs = null, $name = '*')
  {
    if (is_array($msgs)) {
      foreach ($msgs as $msg) {
        $this->messages($type, $msg, $name);
      }
    }
    elseif (! empty($msgs)) {
      $this->messages[$type][$name][md5($msgs)] = $msgs;
    }

    return $this->messages[$type];
  }

  public function warnings($msgs = null, $name = '*')
  {
    return $this->messages(self::MESSAGES_WARNINGS, $msgs, $name);
  }

  public function notices($msgs = null, $name = '*')
  {
    return $this->messages(self::MESSAGES_NOTICES, $msgs, $name);
  }

}
